import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions, URLSearchParams} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {CompanyMoveInfo} from "./company-move-info.class";


@Injectable()
export class CompanyMoveService {

  constructor(private _http: Http) {
  }

  reviewAppr(url: string, id: string, status: string): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    let dataJson;
    if (status === '可申请') {
      dataJson = JSON.stringify({'ids': id});
    } else {
      dataJson = JSON.stringify({'pkid': id});
    }

    return this._http.post(url, dataJson, options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  deleteAppr(url: string, pkids: any[]): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url, JSON.stringify({'pkids': pkids}), options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }


  submit(url: string, info: any): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url, JSON.stringify(info), options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  submitIn(url: string, ids: string): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    let body = {'ids': ids};

    return this._http.post(url, JSON.stringify(body), options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  getEnterpriseInfo(url: string): Promise<any> {
    return this._http.get(url).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  submitAppr(url: string, apprInfo: any): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url, JSON.stringify(apprInfo), options)
      .toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      if (error.status > 200) {
        errMsg = '网络异常';
      } else {
        errMsg = '网络异常';
      }
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    return Promise.reject(errMsg);
  }

}
